package me.leiusual.sharing.pref.impl

import android.content.SharedPreferences
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty

/**
 * Created by usualm on 2018/5/17
 *
 * 不用反射就每个类型写了一遍。
 */
class KDelegate {

  /**
   * String
   */
  class KString(
      private val sp: SharedPreferences, val defaultValue: String? = null
  ) : ReadWriteProperty<Any, String?> {
    override fun getValue(thisRef: Any, property: KProperty<*>): String? {
      return sp.getString(property.name, defaultValue)
    }

    override fun setValue(thisRef: Any, property: KProperty<*>, value: String?) {
      sp.edit().putString(property.name, value).apply()
    }
  }

  /**
   * Set<String>
   */
  class KStringSet(
      private val sp: SharedPreferences, val defaultValue: Set<String>? = null
  ) : ReadWriteProperty<Any, Set<String>?> {
    override fun getValue(thisRef: Any, property: KProperty<*>): Set<String>? {
      return sp.getStringSet(property.name, defaultValue)
    }

    override fun setValue(thisRef: Any, property: KProperty<*>, value: Set<String>?) {
      sp.edit().putStringSet(property.name, value).apply()
    }
  }

  /**
   * Int
   */
  class KInt(
      private val sp: SharedPreferences, val defaultValue: Int = 0
  ) : ReadWriteProperty<Any, Int> {
    override fun getValue(thisRef: Any, property: KProperty<*>): Int {
      return sp.getInt(property.name, defaultValue)
    }

    override fun setValue(thisRef: Any, property: KProperty<*>, value: Int) {
      sp.edit().putInt(property.name, value).apply()
    }
  }

  /**
   * Long
   */
  class KLong(
      private val sp: SharedPreferences, val defaultValue: Long = 0
  ) : ReadWriteProperty<Any, Long> {
    override fun getValue(thisRef: Any, property: KProperty<*>): Long {
      return sp.getLong(property.name, defaultValue)
    }

    override fun setValue(thisRef: Any, property: KProperty<*>, value: Long) {
      sp.edit().putLong(property.name, value).apply()
    }
  }

  /**
   * Float
   */
  class KFloat(
      private val sp: SharedPreferences, val defaultValue: Float = 0f
  ) : ReadWriteProperty<Any, Float> {
    override fun getValue(thisRef: Any, property: KProperty<*>): Float {
      return sp.getFloat(property.name, defaultValue)
    }

    override fun setValue(thisRef: Any, property: KProperty<*>, value: Float) {
      sp.edit().putFloat(property.name, value).apply()
    }
  }

  /**
   * Boolean
   */
  class KBoolean(
      private val sp: SharedPreferences, val defaultValue: Boolean = false
  ) : ReadWriteProperty<Any, Boolean> {
    override fun getValue(thisRef: Any, property: KProperty<*>): Boolean {
      return sp.getBoolean(property.name, defaultValue)
    }

    override fun setValue(thisRef: Any, property: KProperty<*>, value: Boolean) {
      sp.edit().putBoolean(property.name, value).apply()
    }
  }
}